import {getMyMenuPrivilege, getUserInfo, login, logout} from '@/api/user'
import {getToken, removeToken, setToken} from '@/utils/auth'
import router, {resetRouter} from '@/router'

const state = {
  userInfo: {},
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  //是否从后台获取过权限，退出登录时要清空
  hasFetchPrivilege: false,
  //后台获取的资源菜单的:pkey
  myMenuPrivilege: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_FETCH_PRIVILEGE: (state, v) => {
    state.hasFetchPrivilege = v
  },
  SET_MY_MENU_PRIVILEGE: (state, myMenuPrivilege) => {
    state.myMenuPrivilege = myMenuPrivilege
  }
}

const actions = {
  // user login
  login({commit}, userInfo) {
    const {username, password} = userInfo
    return new Promise((resolve, reject) => {
      login({username: username.trim(), password: password}).then(response => {
        const {data} = response
        console.log("登录后信息：", data)
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  //获取个人菜单权限，每个菜单对应一个唯一:pkey
  getMyMenuPrivilege({commit, state}) {
    return new Promise((resolve, reject) => {
      getMyMenuPrivilege().then(response => {
        const {data} = response
        if (!data) {
          reject('无法获取个人权限.')
        }
        console.log("获取到权限为：", data)
        commit('SET_MY_MENU_PRIVILEGE', data)
        commit('SET_FETCH_PRIVILEGE', true)
        resolve(data);
      }).catch(error => reject("获取权限菜单错误" + error))
    })
  },

  // get user info
  getUserInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(response => {
        const {data} = response
        if (!data) {
          reject('无法获取个人信息，请重新登录.')
        }
        console.log("获取到的用户信息为：", data)
        commit("SET_USER_INFO", data)
        const {username, avatar} = data
        commit('SET_NAME', username)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        console.log("获取个人信息报错", error)
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state, dispatch}) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_TOKEN', '')
        commit('SET_MY_MENU_PRIVILEGE', [])
        commit('SET_FETCH_PRIVILEGE', false)
        removeToken()
        resetRouter()
        // dispatch('tagsView/delAllViews', null, {root: true})
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({commit, dispatch}, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const {roles} = await dispatch('getUserInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {root: true})
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, {root: true})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
